import AutoTable from '@/components/AutoTable';
import React, { useState, useEffect, useRef } from 'react';
import { ProForm, ProFormSelect, ProFormText, ProFormDigit, ProFormTextArea } from '@ant-design/pro-components';
import { Avatar, Button, Input, message, Modal, theme, Switch } from 'antd';
import PointsChangeTable from './components/usage';
import ProjectTable from './components/projects';
import Users from './components/users';
import { useModel } from '@umijs/max';

import { doFetch, getFetch } from '@/utils/doFetch';

function Orgs() {
  const [pwd, setPwd] = useState(null);
  const { token } = theme.useToken();
  const {
    initialState: { currentUser, curpro },
    setInitialState
  } = useModel('@@initialState');

  const columns = [
    {
      title: '服务商名称',
      dataIndex: 'orgName',
      key: 'orgName',
      width: 240,
      render: (text, record) => {
        return <a style={{ color: token?.colorPrimary }} onClick={() => viewTrend(record)}>
          <b>{text}</b>
        </a>;
      }
    },
    {
      title: '积木',
      dataIndex: 'block',
      key: 'block',
      width: 68,
      sorter: (a, b) => a.block - b.block,
      search: false,
    },
    {
      title: '项目',
      dataIndex: 'projectNum',
      key: 'projectNum',
      search: false,
      width: 68,
      sorter: (a, b) => a.projectNum - b.projectNum,
    },
    {
      title: '人员',
      dataIndex: 'userNum',
      key: 'userNum',
      search: false,
      width: 68,
      sorter: (a, b) => a.userNum - b.userNum,
    },
    {
      title: '管理员',
      dataIndex: 'userNames',
      key: 'adminName',
      width: 120,
      render: (text) => <a className="text-blue-600 hover:text-blue-900">{text}</a>,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      key: 'remarks',
      search: false
    },
    {
      title: '邀请链接',
      dataIndex: 'state',
      key: 'state',
      search: false,
      render: (_, { id, shareType }) => {
        return <div className='centerl gap12'>
          <Switch defaultChecked={shareType === 1} onChange={(val) => {
            if (val) {
              doFetch({ url: "/org/" + id, params: { shareType: 1 }, method: "PUT" }).then(() => {
                actionRef?.current?.reload();
              });
            } else {
              doFetch({ url: "/org/" + id, params: { shareType: 2 }, method: "PUT" }).then(() => {
                actionRef?.current?.reload();
              });
            }
          }}></Switch>
          {
            shareType === 1 && <a type='text' onClick={() => {
              navigator.clipboard.writeText(`${location.origin}/dev/#/invoke?uid=${currentUser?.id}&oid=${id}&type=admin`).then(() => {
                message.success('邀请链接已复制到剪切板！');
              }).catch(err => {
                message.error('复制失败:' + err);
              });
            }} key='edit'>复制</a>
          }


        </div>;
      }
    },

    {
      title: '操作',
      key: 'action',
      valueType: "option",
      width: 148,
      render: (_, record) => (
        [
          <div key='switch'>
            <Switch checkedChildren={"启用"} unCheckedChildren={"停用"} defaultChecked={record.state === 1} onChange={(e) => {
              if (!e) {
                doFetch({ url: `/org/${record.id}/2`, params: {}, method: "PUT" })
              } else {
                doFetch({ url: `/org/${record.id}/1`, params: {}, method: "PUT" })
              }
            }}></Switch>
          </div>
          ,
          <Button type='link' onClick={() => editCompany(record)} key='edit'>编辑</Button>

        ]
      ),
    },
  ];

  const actionRef = useRef();

  function editCompany(record) {
    setModal((s) => ({
      ...s,
      open: true,
      title: '编辑服务商',
      initialValues: record,
      id: record.id
    }));
  }

  function viewTrend(record) {
    setModal((s) => ({
      ...s,
      open: true,
      title: <span>查看服务商: <b> {record?.orgName} </b> 的详情</span>,
      item: record
    }));
  }

  const [modal, setModal] = useState({
    open: false,
    footer: false,
    onCancel: () => {
      setModal((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  return (
    <>
      <Modal {...modal} destroyOnClose width={!modal?.title?.length ? 1300 : 600}>
        {
          !modal?.title?.length ?
            <div>
              <PointsChangeTable item={modal.item}></PointsChangeTable>
              <ProjectTable item={modal.item}></ProjectTable>
              <Users item={modal.item}></Users>
            </div>
            :
            <ProForm
              initialValues={modal.initialValues}
              style={{ marginTop: 30 }}
              onFinish={async (values) => {
                const extraid = modal.title === '编辑服务商' ? `/${modal.id}` : ''
                let res = await doFetch({
                  url: '/org' + extraid,
                  params: {
                    ...values,
                  },
                  method: modal.title === '编辑服务商' ? 'PUT' : 'POST',
                });
                if (res?.code === 0) {
                  message.success('创建成功!');
                  actionRef.current.reload();
                  setModal((s) => ({
                    ...s,
                    open: false,
                  }));
                }
              }}
            >
              <ProFormText
                label={'服务商名称'}
                name="orgName"
                required
                formItemProps={{
                  rules: [
                    {
                      required: true,
                      message: '请输入服务商名称!',
                    },
                  ],
                }}
              ></ProFormText>
              <ProFormDigit
                label={'服务商积木数量'}
                name="block"
                required
                formItemProps={{
                  rules: [
                    {
                      required: true,
                      message: '请输入服务商积木数量!',
                    },
                  ],
                }}
              ></ProFormDigit>

              <ProFormSelect
                request={async () => {
                  let res = await getFetch({
                    url: '/user/getOrgUserSelection',
                    params: {},
                  });
                  return res?.data?.dataList;
                }}
                placeholder="请选择"
                rules={[{ required: true, message: '请选择服务商管理员!' }]}
                mode="multiple"
                label={'选择服务商管理员'}
                name="operatorIdList"
                // fieldProps={{
                //   maxCount: 1,
                // }}
                required
              ></ProFormSelect>
              <ProFormTextArea
                label={'备注'}
                name="remarks"
              ></ProFormTextArea>
            </ProForm>
        }


      </Modal>
      <AutoTable
        actionRef={actionRef}
        headerTitle="服务商管理"
        columns={columns}
        method='post'
        actions={[
          <Button key="add" type='primary' onClick={() => {
            setModal((s) => ({
              ...s,
              open: true,
              title: "添加服务商",
              initialValues: null,
              id: null
            }));
          }}>
            添加服务商
          </Button>
        ]}
        path={"/org/getOrgPage"}
      ></AutoTable>
    </>

  );
}

export default Orgs;


